#!/bin/bash
#
# Build Julia System Image for GSICoreAnalysis.jl
#
# This script builds a custom Julia system image that significantly speeds up
# Julia GSI execution by pre-compiling all dependencies and commonly used code.
#
# Expected Performance Improvements:
#   - Startup time: 5-10× faster (from ~5s to <1s)
#   - First execution: 2-3× faster (no JIT compilation)
#   - Overall workflow: 2-4× faster
#

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_header() {
    echo ""
    echo "=========================================================================="
    echo -e "${BLUE}$1${NC}"
    echo "=========================================================================="
    echo ""
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

print_info() {
    echo -e "${BLUE}ℹ${NC} $1"
}

GSI_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
JULIA_BIN=${JULIA_BIN:-julia}
SYSIMAGE_NAME="GSICoreAnalysis.so"
SYSIMAGE_PATH="${GSI_ROOT}/${SYSIMAGE_NAME}"

print_header "Julia System Image Builder for GSICoreAnalysis.jl"

echo "Configuration:"
echo "  GSI Root:       ${GSI_ROOT}"
echo "  Julia Binary:   ${JULIA_BIN}"
echo "  System Image:   ${SYSIMAGE_PATH}"
echo ""

# Force GR to run headless to avoid Qt/Wayland warnings during precompile
export GKSwstype=nul

# Check Julia is available
if ! command -v "${JULIA_BIN}" &> /dev/null; then
    print_error "Julia not found. Please install Julia or set JULIA_BIN environment variable."
    exit 1
fi

print_success "Julia found: $(${JULIA_BIN} --version)"

# Check if system image already exists
if [ -f "${SYSIMAGE_PATH}" ]; then
    print_warning "System image already exists: ${SYSIMAGE_PATH}"
    echo ""
    read -p "Do you want to rebuild it? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        print_info "Keeping existing system image"
        exit 0
    fi
    print_info "Removing old system image..."
    rm -f "${SYSIMAGE_PATH}"
fi

# Build system image
print_header "Building System Image"

print_info "This will take 5-15 minutes depending on your system..."
print_info "Building with native CPU optimizations..."
echo ""

cd "${GSI_ROOT}"

# Run the Julia build script
if "${JULIA_BIN}" build_sysimage.jl \
    --output "${SYSIMAGE_NAME}" \
    --cpu-target native; then

    print_header "Build Complete!"

    # Get file size
    if [ -f "${SYSIMAGE_PATH}" ]; then
        FILESIZE=$(du -h "${SYSIMAGE_PATH}" | cut -f1)
        print_success "System image created: ${SYSIMAGE_PATH}"
        print_success "Size: ${FILESIZE}"
    fi

    echo ""
    echo "Usage Instructions:"
    echo "──────────────────────────────────────────────────────────────────────"
    echo ""
    echo "Use the system image with:"
    echo "  ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} your_script.jl"
    echo ""
    echo "Examples:"
    echo "  # Run operational GSI analysis with speedup"
    echo "  ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} demos/operational_gsi_analysis.jl"
    echo ""
    echo "  # Run diagnostic checking with speedup"
    echo "  ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} scripts/check_diagnostics.jl"
    echo ""
    echo "  # Run validation with speedup"
    echo "  ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} validation/validate_diagnostic_files.jl"
    echo ""
    echo "Performance Improvements:"
    echo "──────────────────────────────────────────────────────────────────────"
    echo "  • Startup time:      ~5-10× faster (5s → <1s)"
    echo "  • First execution:   ~2-3× faster (no JIT)"
    echo "  • Overall workflow:  ~2-4× faster"
    echo "  • Total speedup:     Could match or exceed Fortran GSI!"
    echo ""

    # Update run scripts to use system image
    print_header "Updating Scripts"

    DEMO_SCRIPT="demos/operational_gsi_analysis.jl"
    if [ -f "${DEMO_SCRIPT}" ]; then
        # Add shebang if not present
        if ! head -1 "${DEMO_SCRIPT}" | grep -q "^#!"; then
            print_info "Adding system image hint to ${DEMO_SCRIPT}..."
            # Create backup
            cp "${DEMO_SCRIPT}" "${DEMO_SCRIPT}.bak"
            # Add comment at top
            echo "#!/usr/bin/env -S julia --sysimage=GSICoreAnalysis.so" > "${DEMO_SCRIPT}.new"
            echo "# For faster execution, run with: julia --sysimage=GSICoreAnalysis.so $(basename ${DEMO_SCRIPT})" >> "${DEMO_SCRIPT}.new"
            cat "${DEMO_SCRIPT}" >> "${DEMO_SCRIPT}.new"
            mv "${DEMO_SCRIPT}.new" "${DEMO_SCRIPT}"
            print_success "Updated ${DEMO_SCRIPT}"
        fi
    fi

    print_header "Setup Complete!"

    echo ""
    echo "Next Steps:"
    echo "──────────────────────────────────────────────────────────────────────"
    echo "  1. Test the system image:"
    echo "     ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} -e 'println(\"System image works!\")'"
    echo ""
    echo "  2. Benchmark the speedup:"
    echo "     time ${JULIA_BIN} demos/operational_gsi_analysis.jl  # Without sysimage"
    echo "     time ${JULIA_BIN} --sysimage=${SYSIMAGE_NAME} demos/operational_gsi_analysis.jl  # With sysimage"
    echo ""
    echo "  3. Use in production:"
    echo "     Update your workflow to always use --sysimage=${SYSIMAGE_NAME}"
    echo ""

else
    print_header "Build Failed"
    print_error "System image build failed. Check the output above for errors."
    echo ""
    echo "Common issues:"
    echo "  • PackageCompiler.jl not installed - run: julia -e 'using Pkg; Pkg.add(\"PackageCompiler\")'"
    echo "  • Insufficient disk space - need ~500MB free"
    echo "  • Permission issues - check write access to ${GSI_ROOT}"
    echo ""
    exit 1
fi
